package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.annotation.FeishuTableInterface;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.admin.dto.ErpTransferStatusDTO;
import org.springblade.modules.admin.dto.PartsWorkSaveDTO;
import org.springblade.modules.admin.entity.MaintainPartsWork;
import org.springblade.modules.admin.entity.MaintainPartsWorkSku;
import org.springblade.modules.admin.entity.MaintainPlanContentExt;
import org.springblade.modules.admin.entity.PartAddress;
import org.springblade.modules.admin.enums.SourceEnum;
import org.springblade.modules.admin.service.IMaintainPlanContentExtService;
import org.springblade.modules.admin.service.IPartAddressService;
import org.springblade.modules.admin.service.MaintainPartsWorkService;
import org.springblade.modules.admin.service.parts.OrderStateMachineService;
import org.springblade.modules.admin.utils.AsyncUtils;
import org.springblade.modules.admin.vo.BusinessApproveVO;
import org.springblade.modules.admin.vo.parts.PartsWorkDetailVO;
import org.springblade.modules.system.entity.Region;
import org.springblade.modules.system.service.IRegionService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author zcc
 * @version 1.0
 * @date 2023/9/4 18:53
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("admin/maintain/parts/work")
public class MaintainPartsWorkController {

	private final MaintainPartsWorkService partsWorkService;
	private final IPartAddressService partAddressService;
	private final IRegionService regionService;
	private final IMaintainPlanContentExtService planContentExtService;
	private final OrderStateMachineService orderStateMachineService;
	private final AsyncUtils asyncUtils;
	private final ProjectApiConfiguration projectApiConfiguration;

	/**
	 * 获取部件更换详情
	 *
	 * @param planId
	 * @return
	 */
	@GetMapping("/detail")
	public R<PartsWorkDetailVO> selectPartsWorkDetail(Long planId) {
		return R.data(partsWorkService.selectPartsWorkDetail(planId));
	}


	@PostMapping("/update")
	public R<Boolean> update(@RequestBody MaintainPartsWork maintainPartsWork) {
		PartAddress partAddress = maintainPartsWork.getPartAddress();
		partAddress.setPlanId(maintainPartsWork.getPlanId());
		if (StrUtil.isNotEmpty(partAddress.getAdCode())) {
			List<Region> regions = regionService.list(Wrappers.<Region>lambdaQuery().eq(Region::getDistrictCode, partAddress.getAdCode()));
			if (regions.size() > 0) {
				partAddress.setProvinceName(regions.get(0).getProvinceName());
				partAddress.setCityName(regions.get(0).getCityName());
				partAddress.setAdName(regions.get(0).getDistrictName());
			}
		}
		partAddressService.saveOrUpdate(partAddress);

		MaintainPlanContentExt maintainPlanContentExt = planContentExtService.getOne(Wrappers.<MaintainPlanContentExt>lambdaQuery().eq(MaintainPlanContentExt::getPlanId,maintainPartsWork.getPlanId()));
		maintainPlanContentExt.setEmerProcType(maintainPartsWork.getEmerProcType());
		maintainPlanContentExt.setWorkOrderType(maintainPartsWork.getWorkOrderType());
		planContentExtService.updateById(maintainPlanContentExt);
		return R.data(partsWorkService.updateById(maintainPartsWork));
	}

	@PostMapping("/partsSave")
	@ApiOperation(value = "新增配件工单")
	public R partsSave(@Valid @RequestBody PartsWorkSaveDTO partsWorkSave) {
		String url = projectApiConfiguration.getMaintain() + "/maintain/parts/work/partsSave";
		String res = null;
		try {
			res = HttpUtil.createPost(url).header(TokenConstant.HEADER, AuthUtil.getHeader(WebUtil.getRequest())).timeout(10000).body(JSONObject.toJSONString(partsWorkSave)).execute().body();
		} catch (HttpException e) {
			log.error("请求梯无忧小程序接口失败，url: " + url);
			return R.fail("请求梯无忧小程序接口失败");
		}

		JSONObject jsonObject = JSONObject.parseObject(res);
		if (jsonObject.getBoolean("success")) {
			return R.status(true);
		} else {
			return R.fail(jsonObject.getString("msg"));
		}
	}

	@PostMapping("/approve")
	@ApiOperation(value = "配件执行审批")
	public R approve(@Valid @RequestBody BusinessApproveVO businessApprove) {
		String url = projectApiConfiguration.getMaintain() + "/repair/business/flow/5/approve";
		String res = null;
		try {
			res = HttpUtil.createPost(url).header(TokenConstant.HEADER, AuthUtil.getHeader(WebUtil.getRequest())).timeout(10000).body(JSONObject.toJSONString(businessApprove)).execute().body();
		} catch (HttpException e) {
			log.error("请求梯无忧小程序接口失败，url: " + url);
			return R.fail("请求梯无忧小程序接口失败");
		}

		JSONObject jsonObject = JSONObject.parseObject(res);
		if (jsonObject.getBoolean("success")) {
			return R.status(true);
		} else {
			return R.fail(jsonObject.getString("msg"));
		}
	}

	@FeishuTableInterface
	@ApiOperation(value = "配件工单状态推进")
	@PostMapping("/transfer/status")
	public Object transferStatus(@RequestBody Map<String, Object> params) {
		return orderStateMachineService.execute(params);
	}

	@ApiOperation(value = "ERP配件工单状态推进")
	@PostMapping("/erp/transfer/status")
	public R erpTransferStatus(@RequestBody ErpTransferStatusDTO params) {
		partsWorkService.erpTransferStatus(params);
		return R.status(true);
	}

	@ApiOperation(value = "配件菜单角标统计")
	@GetMapping("part/approve/icon")
	public R partApproveIcon() {
		return R.data(partsWorkService.partApproveIcon());
	}

	@GetMapping("/script")
	@ApiOperation(value = "配件信息脚本")
	public R<Boolean> script(@RequestParam String planIds) {
		return R.data(partsWorkService.script(Func.toLongList(planIds)));
	}

	@PutMapping("/sku/submit/{planId}")
	public R<Boolean> skuSubmit(@PathVariable Long planId,@RequestBody List<MaintainPartsWorkSku> skuList){
		return R.data(partsWorkService.skuSubmit(planId,skuList));
	}
}
